<template>
  <div id="main">
    <div id="form">
      <el-form ref="phone" :model="phone" label-width="100px" class="demo-ruleForm" :rules="rules">
        <el-form-item
          label="客服电话"
          prop="number"
        >
          <el-input v-model="phone.number" maxlength="11" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
        </el-form-item>
      </el-form>
      <div id="buttons">
        <el-button type="primary" @click="submitPhone('phone')">添加/修改</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getPhone, updatePhone } from '@/api/phone'
export default {
  data() {
    var checkphone = (rule, value, callback) => {
    // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    return {
      phone: {
        number: ''
      },
      type: '',
      rules: {
        number: [{ validator: checkphone, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getPhone().then((resp) => {
        this.phone.number = resp.obj.servicePhoneNumber
      })
    },
    submitPhone(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updatePhone(this.phone.number).then((resp) => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    isCellPhone(val) {
      if (!/^1[3456789]\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style scoped>
  #main{
    width: 100%;
  }

  #form{
    border: #E4E7ED 1px solid;
    border-radius: 30px;
    padding: 50px;
    margin: 50px auto;

    width: 900px;

  }
  #buttons{
    text-align: center;
  }
  input::-webkit-outer-spin-button,input::-webkit-inner-spin-button{
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    -o-appearance: none !important;
    -ms-appearance: none !important;
    appearance: none !important;
    margin: 0;
  }
  input[type="number"]{
    -webkit-appearance:textfield;
    -moz-appearance:textfield;
    -o-appearance:textfield;
    -ms-appearance:textfield;
    appearance:textfield;
  }
</style>
